<?php

namespace app\api\model;

use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class Category extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    // 判断是否为私密板块
    public static function checkPrivate($pid)
    {
        $cate = self::where(['id' => $pid])->find();
        if ($cate['is_hide'] == 1) return true;
        return false;
    }
    public function getIconAttr($val)
    {
        $path = app()->getRootPath() . 'public' . $val;
        if (empty($val) || !file_exists($path)) {
            return addHost('/static/images/noimg.png');
        }
        return addHost($val);
    }
    
    // 版主
    public function getCategoryWithModerators($categoryId)
    {
        // 获取分类信息
        $category = $this->where(['id' => $categoryId, 'pid' => 0])->find();
        if (!$category) {
            return null;
        }

        // 分类数据转数组
        $categoryData = $category->toArray();

        // 如果没有版主
        if (empty($categoryData['moderator'])) {
            $categoryData['moderators'] = [];
            return $categoryData;
        }

        // 将逗号分隔的版主ID转为数组
        $moderatorIds = array_filter(explode(',', $categoryData['moderator']));

        // 查询版主用户信息
        $moderators = Db::name('user')
            ->field(['id', 'nickname', 'avator'])
            ->whereIn('id', $moderatorIds)
            ->select()
            ->toArray();

        // 将版主信息添加到返回数据中
        $categoryData['moderators'] = $moderators;

        return $categoryData;
    }
}
